package com.shhm.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shhm.common.entity.admin.SysRoleOperatePerms;
import com.shhm.common.mapper.SysRoleOperatePermsMapper;
import jakarta.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;


/**
 * @author JackZ
 * @version 1.0
 * @description: TODO
 * @date 2025/8/6 下午4:10
 */
public class RequestUtil {
    /**
     * 操作权限优先算法,以最多权限的角色权限优先
     * @param request
     * @param roleOperatePermsMapper
     * @return 操作权限字符
     */
    public static String getUserOperatePerms(HttpServletRequest request, SysRoleOperatePermsMapper roleOperatePermsMapper){
        String res="";
        String reqURI = request.getRequestURI();
        String token = JwtUtil.handleAuthorizationString(request.getHeader("Authorization"));
        if (JwtUtil.isExpired(token)) {
            return "NOT_PERMISSION";
        }
        List<String> roleFromToken = JwtUtil.getRoleFromToken(token);

        List<String> handleRole = new ArrayList<>();
        roleFromToken.forEach(r->handleRole.add(r.substring(5)));

        QueryWrapper<SysRoleOperatePerms> wapper = new QueryWrapper<>();
        wapper.select("operate_str")
                .in("role_key",handleRole)
                .eq("request_uri",reqURI);
        List<SysRoleOperatePerms> list = roleOperatePermsMapper.selectList(wapper);
        if(list==null || list.isEmpty()){
            return "NOT_PERMISSION";
        }

        if (list.size()>1){
            for (SysRoleOperatePerms srop : list) {
                String operateStr = srop.getOperateStr();
                if (operateStr.equals("*")) {
                    res = operateStr;
                    break;
                }
                if (operateStr.length()>res.length()) res=operateStr;
            }
        }else {
//            if (list.isEmpty()) res="NOT_PERMISSION";
//            else res=list.get(0).getOperateStr();
            res=list.get(0).getOperateStr();
        }
        return res;
    }


}
